package yo.latyoo.hokage.skmr.trigger;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yo.latyoo.hokage.skmr.biz.domain.JobLog;
import yo.latyoo.hokage.skmr.biz.model.JobModel;
import yo.latyoo.hokage.skmr.biz.repository.JobLogRepo;
import yo.latyoo.hokage.skmr.configuration.SkmrConfiguration;
import yo.latyoo.hokage.tools.consts.LogConst;
import yo.latyoo.hokage.tools.parameter.HO;
import yo.latyoo.hokage.tools.parameter.TriggerParam;
import yo.latyoo.hokage.tools.route.RouteEnum;
import yo.latyoo.hokage.tools.util.IdUtil;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

public class JobTrigger {
    private static final Logger logger = LoggerFactory.getLogger(JobTrigger.class);

    public static void trigger(final JobModel job){
        if(job == null){
            logger.warn(LogConst.PREFIX + " job is null");
            return;
        }
        if(job.registryList.isEmpty()){
            logger.warn(LogConst.PREFIX + " executor address empty! job:{}",  job.jobDesc);
            return;
        }

        Thread.startVirtualThread(()->{
            List<String> registryList = job.registryList;
            if (Objects.requireNonNull(job.routeType) == RouteEnum.SHARDING_BROADCAST) {
                int registrySize = registryList.size();
                int size = (job.shardingIndex == 0) ? registryList.size() : job.shardingIndex;
                int index = 0;
                for (int i = 0; i < size; i++) {
                    if (index == registrySize)
                        index = 0;
                    processTrigger(job, index, size, registryList.get(index));
                    index++;
                }
            } else {
                HO<String> routeR = job.routeType.getRoute().execute(null, registryList);
                processTrigger(job, 0, 1, routeR.data);
            }
        });
    }

    private static void processTrigger(JobModel jobInfo, int index, int total,String address) {
        LocalDateTime now = LocalDateTime.now();
        TriggerParam triggerParam = new TriggerParam();
        triggerParam.setJobId(jobInfo.id);
        triggerParam.setTraceId(IdUtil.id());
        triggerParam.setHandlerMethod(jobInfo.handlerMethod);
        triggerParam.setHandlerParams(jobInfo.handlerParams);
        triggerParam.setTimeout(jobInfo.timeout);
        triggerParam.setRetryTimes(jobInfo.failRetryCount);
        triggerParam.setBroadcastIndex(index);
        triggerParam.setBroadcastTotal(total);
        JobLogRepo jobLogRepo = SkmrConfiguration.getConfig().getJobLogRepo();
        JobLog jobLog = new JobLog();
        jobLog.setId(triggerParam.getTraceId());
        jobLog.setJobId(jobInfo.id);
        //jobLog.setJobGroup(jobInfo.getJobGroup().getId());
        jobLog.setTargetAddress(address);
        jobLog.setTargetParam(jobInfo.handlerParams);
        jobLog.setTargetHandlerMethod(jobInfo.handlerMethod);
        jobLog.setCreatedAt(now.toLocalDate());
        jobLogRepo.saveAndFlush(jobLog);
        HO<String> result = runExecutor(triggerParam, address);
        assert result != null;
        jobLogRepo.updateTrigger(result.code,result.msg,now,jobLog.getId());
    }

    private static HO<String> runExecutor(TriggerParam triggerParam, String address) {

        //RI<String> result = HttpUtil.post(address + "/latyoo-job/run", JobConfig.getConfig().getAccessToken(), triggerParam);
        /*if(result.code == RI.SERVER_ERROR){
            for(int i = 0;i < triggerParam.getRetry)
        }*/
        //logger.info(LogConst.PREFIX + "trigger run result: {}",result.toString());
        return null;
    }

/*    public static RI<String> cancel(TriggerParam triggerParam, String address){
        RI<String> result = HttpUtil.post(address.concat("/latyoo-job")
                .concat(triggerParam.getJobId().toString())
                .concat("/cancel"), JobConfig.getConfig().getAccessToken(), triggerParam);
        logger.info(LogConst.PREFIX + "trigger cancel result: {}",result.toString());
        return result;
    }*/
}
